package com.design.pattern.proxy.protectProxy;

import java.lang.reflect.Proxy;

public class ProtectProxyTest {
    public static void main(String[] args) {
        ProtectProxyTest proxyTest = new ProtectProxyTest();

        proxyTest.drive();
    }

    public void drive() {
        PersonBean joe = getPersonBean("joe");
        PersonBean ownerProxy = getOwnerProxy(joe);
        System.out.println("代理类：" + ownerProxy.getClass() + ";普通类：" + joe.getClass());

        System.out.println("拥有者名称:" + ownerProxy.getName());
        ownerProxy.setInterests("bowling Go");
        System.out.println("Interests set from owner proxy");
        try {
            ownerProxy.setHotOrNotRating(10);
        } catch (Exception e) {
            System.out.println("can`t set owner ration from proxy");
        }
        System.out.println(ownerProxy.getHotOrNotRating());


        PersonBean nonOwnerProxy = getNonOwnerProxy(joe);
        System.out.println("代理类：" + nonOwnerProxy.getClass() + ";普通类：" + joe.getClass());

        System.out.println("拥有者名称:" + nonOwnerProxy.getName());
        nonOwnerProxy.setHotOrNotRating(8);
        try {
            nonOwnerProxy.setInterests("bowling Go");
            System.out.println("Interests set from owner proxy");
        } catch (Exception e) {
            System.out.println("can`t set nonOwner interests from proxy");
        }
        System.out.println(nonOwnerProxy.getHotOrNotRating());

    }

    public PersonBean getPersonBean(String name) {
        PersonBean personBean = new PersonBeanImpl();
        personBean.setName(name);
        personBean.setGender("gender");
        personBean.setInterests("interests");
        personBean.setHotOrNotRating(7);
        return personBean;
    }

    public PersonBean getOwnerProxy(PersonBean personBean) {
        return (PersonBean) Proxy.newProxyInstance(personBean.getClass().getClassLoader(), personBean.getClass().getInterfaces(), new OwnerInvocationHandler(personBean));
    }

    public PersonBean getNonOwnerProxy(PersonBean personBean) {
        return (PersonBean) Proxy.newProxyInstance(personBean.getClass().getClassLoader(), personBean.getClass().getInterfaces(), new NonOwnerInvocationHandler(personBean));
    }
}